<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="爬虫,Python," />


<meta name="description" content="介绍 Scrapy是一个纯Python编写，为了爬取网站数据，提取结构性数据而编写的应用框架。 Scrapy 框架工作原理 组件  ScrapyEngine (引擎)   引擎相当于Scrapy的心脏,负责控制数据在各组件之间流动,并在相应动作发生时触发事件   Scheduler (调度器) 引擎将要处理的request交给调度器排队等候,等待引擎调用后返回request">
<meta name="keywords" content="爬虫,Python">
<meta property="og:type" content="article">
<meta property="og:title" content="Scrapy 框架的原理以及简单使用">
<meta property="og:url" content="http://blog.yunshu168.com/posts/d801fc43.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="介绍 Scrapy是一个纯Python编写，为了爬取网站数据，提取结构性数据而编写的应用框架。 Scrapy 框架工作原理 组件  ScrapyEngine (引擎)   引擎相当于Scrapy的心脏,负责控制数据在各组件之间流动,并在相应动作发生时触发事件   Scheduler (调度器) 引擎将要处理的request交给调度器排队等候,等待引擎调用后返回request">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/006tNbRwgy1g9iaugwzapj312g0nijv2.jpg">
<meta property="og:updated_time" content="2019-12-04T11:25:35.721Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Scrapy 框架的原理以及简单使用">
<meta name="twitter:description" content="介绍 Scrapy是一个纯Python编写，为了爬取网站数据，提取结构性数据而编写的应用框架。 Scrapy 框架工作原理 组件  ScrapyEngine (引擎)   引擎相当于Scrapy的心脏,负责控制数据在各组件之间流动,并在相应动作发生时触发事件   Scheduler (调度器) 引擎将要处理的request交给调度器排队等候,等待引擎调用后返回request">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/006tNbRwgy1g9iaugwzapj312g0nijv2.jpg">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/d801fc43.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>Scrapy 框架的原理以及简单使用 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/d801fc43.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Scrapy 框架的原理以及简单使用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-02T12:37:05+08:00">2017-07-02</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p> Scrapy是一个纯Python编写，为了爬取网站数据，提取结构性数据而编写的应用框架。</p>
<h3 id="Scrapy-框架工作原理"><a href="#Scrapy-框架工作原理" class="headerlink" title="Scrapy 框架工作原理"></a>Scrapy 框架工作原理</h3><p><img src="https://tva1.sinaimg.cn/large/006tNbRwgy1g9iaugwzapj312g0nijv2.jpg" alt="scrapy架构"></p>
<h4 id="组件"><a href="#组件" class="headerlink" title="组件"></a>组件</h4><p>  ScrapyEngine (引擎)  </p>
<pre><code>引擎相当于Scrapy的心脏,负责控制数据在各组件之间流动,并在相应动作发生时触发事件
</code></pre><p>  Scheduler (调度器)</p>
<pre><code>引擎将要处理的request交给调度器排队等候,等待引擎调用后返回request
</code></pre><a id="more"></a>
<p> Downloader (下载器)</p>
<pre><code>下载器负责获取页面数据,返回response响应给引擎,而后给Spider
</code></pre><p> Downloader(下载器中间件)</p>
<pre><code>下载器中间件位于下载器和引擎之间,处理Downloader返回给引擎的response,通过自定义代码来扩展功能
</code></pre><p>Spider Middlewares (Spider中间件)</p>
<pre><code>Spider中间件位于Spider和引擎之间,处理Spider的输入response和输出Item和requests。
</code></pre><p>Spider (蜘蛛)</p>
<pre><code>Spider是Scrapy用户编写的用于分析和处理Response并返回Item，产生新页面的下载请求
</code></pre><p>  ItemPipeline (管道)</p>
<pre><code>Item Pipeline负责处理被spider提取出来的item。典型的处理有清理、验证及持久化(例如存取到数据库中)。
</code></pre><h4 id="Scrapy的执行流程"><a href="#Scrapy的执行流程" class="headerlink" title="Scrapy的执行流程"></a>Scrapy的执行流程</h4><ol>
<li>允许爬虫，Spider 根据 start_url 生产 Request对象， 提交给 ENGINE</li>
<li>Request 进入 SCHEDULER 排队等待调用</li>
<li>Request 对象从 SCHEDULER 出对交给 ENGINE。</li>
<li>ENGINE 将request交给下载器 Downloader，在Internet进行下载。</li>
<li>Downloader 返回 response 给ENGINE。</li>
<li>ENGINE 判断是 response 将其交给 Spider 进行解析返回 Item 和 requests给。</li>
<li>如果是Item, 引擎将 Item交给 piplines 进行存储等操作, 是 request的话， 交给secheduler排队处理</li>
</ol>
<h3 id="Spider-实例"><a href="#Spider-实例" class="headerlink" title="Spider 实例"></a>Spider 实例</h3><h4 id="入口"><a href="#入口" class="headerlink" title="入口"></a>入口</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line">__author__ = <span class="string">'yunshu'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> scrapy.cmdline <span class="keyword">import</span> execute</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line">sys.path.append(os.path.dirname(os.path.abspath(__file__)))</span><br><span class="line"></span><br><span class="line">execute([<span class="string">'scrapy'</span>, <span class="string">'crawl'</span>, <span class="string">'pythontab'</span>])</span><br></pre></td></tr></table></figure>
<h4 id="Spider"><a href="#Spider" class="headerlink" title="Spider"></a>Spider</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"><span class="keyword">import</span> scrapy</span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">from</span> urllib <span class="keyword">import</span> parse</span><br><span class="line"><span class="keyword">from</span> scrapy.http <span class="keyword">import</span> Request</span><br><span class="line"><span class="keyword">from</span> scrapyspiders.items <span class="keyword">import</span> PythontabItem</span><br><span class="line"><span class="keyword">from</span> scrapyspiders.utils.common <span class="keyword">import</span> get_md5</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PythontabSpider</span><span class="params">(scrapy.Spider)</span>:</span></span><br><span class="line">    name = <span class="string">'pythontab'</span></span><br><span class="line">    allowed_domains = [<span class="string">'www.pythontab.com'</span>]</span><br><span class="line">    start_urls = [<span class="string">'http://www.pythontab.com'</span>]</span><br><span class="line">    categories = &#123;<span class="string">"pythonjichu"</span>: <span class="number">1</span>, <span class="string">"pythonhexinbiancheng"</span>: <span class="number">2</span>, <span class="string">"pythonweb"</span>: <span class="number">3</span>, <span class="string">"hanshu"</span>: <span class="number">4</span>, <span class="string">"pythongui"</span>: <span class="number">5</span>&#125;</span><br><span class="line">    fetched = [<span class="string">'pythonjichu'</span>]</span><br><span class="line"></span><br><span class="line">		<span class="comment">## 调用基类的start_requests()，生成 Request 对象，默认回调方法是 parse()</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> response.status == <span class="number">200</span>:</span><br><span class="line">            <span class="keyword">for</span> category <span class="keyword">in</span> self.categories:</span><br><span class="line">                category_url = self.start_urls[<span class="number">0</span>] + <span class="string">'/html/'</span> + category</span><br><span class="line">                <span class="keyword">yield</span> Request(url=category_url, callback=self.do_parse)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            print(<span class="string">'site error'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">do_parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        <span class="comment"># 解析列表页中的所有文章url并交给scrapy下载后并进行解析</span></span><br><span class="line">        post_urls = response.xpath(<span class="string">'//ul[@id="catlist"]//li//@href'</span>).extract()</span><br><span class="line">        <span class="keyword">for</span> post_url <span class="keyword">in</span> post_urls:</span><br><span class="line">            <span class="keyword">yield</span> Request(url=parse.urljoin(response.url, post_url), callback=self.parse_detail)</span><br><span class="line"></span><br><span class="line">        links = response.xpath(<span class="string">'//div[@id="pages"]//a[@class="a1"]/@href'</span>).extract()</span><br><span class="line">        <span class="comment"># 下一页</span></span><br><span class="line">        <span class="keyword">if</span> len(links) == <span class="number">2</span>:</span><br><span class="line">            <span class="keyword">yield</span> Request(url=parse.urljoin(response.url, links[<span class="number">1</span>]), callback=self.do_parse)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse_detail</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        item = PythontabItem()</span><br><span class="line">        item[<span class="string">'url'</span>] = response.url</span><br><span class="line">        item[<span class="string">'url_object_id'</span>] = get_md5(response.url)</span><br><span class="line">        item[<span class="string">'title'</span>] = response.xpath(<span class="string">"//h1/text()"</span>).extract_first()</span><br><span class="line">        item[<span class="string">'content'</span>] = response.xpath(<span class="string">'//div[@class="content"]'</span>).extract_first()</span><br><span class="line">        item[<span class="string">'create_time'</span>] = datetime.now().strftime(<span class="string">'%Y-%m-%d %H:%M:%S'</span>)</span><br><span class="line">        <span class="comment"># 文章分类</span></span><br><span class="line">        item[<span class="string">'category'</span>] = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> category <span class="keyword">in</span> self.categories:</span><br><span class="line">            <span class="keyword">if</span> category <span class="keyword">in</span> item[<span class="string">'url'</span>]:</span><br><span class="line">                item[<span class="string">'category'</span>] = self.categories[category]</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">yield</span> item</span><br></pre></td></tr></table></figure>
<p><strong>PythontabItem：</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> scrapy</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PythontabItem</span><span class="params">(scrapy.Item)</span>:</span></span><br><span class="line">    url = scrapy.Field()</span><br><span class="line">    url_object_id = scrapy.Field()</span><br><span class="line">    content = scrapy.Field()</span><br><span class="line">    title = scrapy.Field()</span><br><span class="line">    create_time = scrapy.Field()</span><br><span class="line">    category = scrapy.Field()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_insert_sql</span><span class="params">(self)</span>:</span></span><br><span class="line">        insert_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">             insert into pythontab(url_object_id, url, title, content, category, create_time)</span></span><br><span class="line"><span class="string">             VALUES (%s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE content=VALUES(content),title=VALUES(title)</span></span><br><span class="line"><span class="string">         """</span></span><br><span class="line"></span><br><span class="line">        params = (self[<span class="string">'url_object_id'</span>], self[<span class="string">"url"</span>], self[<span class="string">"title"</span>], self[<span class="string">"content"</span>], self[<span class="string">'category'</span>], self[<span class="string">"create_time"</span>])</span><br><span class="line">        <span class="keyword">return</span> insert_sql, params</span><br></pre></td></tr></table></figure></p>
<h5 id="Spider-Middleware"><a href="#Spider-Middleware" class="headerlink" title="Spider Middleware"></a>Spider Middleware</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SPIDER_MIDDLEWARES = &#123;</span><br><span class="line">   <span class="string">'scrapyspiders.middlewares.RandomProxyMiddleware'</span>: <span class="number">533</span>,</span><br><span class="line">   <span class="string">'scrapyspiders.middlewares.RandomUserAgentMiddleware'</span>: <span class="number">543</span>,</span><br><span class="line">   <span class="string">'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware'</span>:<span class="keyword">None</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>中间件实现：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Define here the models for your spider middleware</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># See documentation in:</span></span><br><span class="line"><span class="comment"># http://doc.scrapy.org/en/latest/topics/spider-middleware.html</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> scrapy <span class="keyword">import</span> signals</span><br><span class="line"><span class="keyword">from</span> fake_useragent <span class="keyword">import</span> UserAgent</span><br><span class="line"><span class="keyword">from</span> scripts.get_proxy_ips <span class="keyword">import</span> GetIp</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RandomUserAgentMiddleware</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, crawler)</span>:</span></span><br><span class="line">        super(RandomUserAgentMiddleware, self).__init__()</span><br><span class="line">        self.ua = UserAgent()</span><br><span class="line">        self.ua_type = crawler.settings.get(<span class="string">'RANDOM_UA_TYPE'</span>, <span class="string">'random'</span>)</span><br><span class="line"></span><br><span class="line"><span class="meta">    @classmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">from_crawler</span><span class="params">(cls, crawler)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> cls(crawler);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_request</span><span class="params">(self, request, spider)</span>:</span></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">get_ua</span><span class="params">()</span>:</span></span><br><span class="line">            <span class="keyword">return</span> getattr(self.ua, self.ua_type);</span><br><span class="line"></span><br><span class="line">        ua = get_ua()</span><br><span class="line"></span><br><span class="line">        request.headers.setdefault(<span class="string">'User-Agent'</span>, get_ua())</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 代理ip中间件</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RandomProxyMiddleware</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_request</span><span class="params">(self, request, spider)</span>:</span></span><br><span class="line">        getip = GetIp()</span><br><span class="line">        request.meta[<span class="string">'proxy'</span>] = getip.get_random_ip()</span><br></pre></td></tr></table></figure></p>
<h5 id="获取代理ip"><a href="#获取代理ip" class="headerlink" title="获取代理ip"></a>获取代理ip</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="keyword">import</span> MySQLdb</span><br><span class="line"><span class="keyword">from</span> scrapy.selector <span class="keyword">import</span> Selector</span><br><span class="line"></span><br><span class="line"><span class="comment"># from scrapyspiders.settings import MYSQL_HOST</span></span><br><span class="line"><span class="comment"># from scrapyspiders.settings import MYSQL_DBNAME</span></span><br><span class="line"><span class="comment"># from scrapyspiders.settings import MYSQL_USER</span></span><br><span class="line"><span class="comment"># from scrapyspiders.settings import MYSQL_PASSWD</span></span><br><span class="line"><span class="comment"># from scrapyspiders.settings import MYSQL_CHARSET</span></span><br><span class="line"></span><br><span class="line">conn = MySQLdb.connect(host=<span class="string">'localhost'</span>, user=<span class="string">'root'</span>, passwd=<span class="string">'123456'</span>, db=<span class="string">'spiders'</span>, charset=<span class="string">'utf8'</span>)</span><br><span class="line">cursor = conn.cursor()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 爬取西刺的免费ip代理（http://www.xicidaili.com/）</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_ip</span><span class="params">()</span>:</span></span><br><span class="line">    headers = &#123;</span><br><span class="line">        <span class="string">"User-Agent"</span>:<span class="string">"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"</span></span><br><span class="line">    &#125;</span><br><span class="line">    response = requests.get(<span class="string">'http://www.xicidaili.com/nn/1'</span>, headers=headers)</span><br><span class="line">    <span class="keyword">if</span> response.status_code != <span class="number">200</span>:</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    selector = Selector(text=response.text)</span><br><span class="line">    pagetext = selector.css(<span class="string">'.pagination a::text'</span>).extract()</span><br><span class="line">    pages = int(pagetext[<span class="number">-2</span>:<span class="number">-1</span>][<span class="number">0</span>])</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> page <span class="keyword">in</span> range(pages):</span><br><span class="line">        response = requests.get(<span class="string">'http://www.xicidaili.com/nn/&#123;0&#125;'</span>.format(page+<span class="number">1</span>), headers=headers)</span><br><span class="line">        <span class="keyword">if</span> response.status_code == <span class="number">200</span>:</span><br><span class="line">            selector = Selector(text=response.text)</span><br><span class="line">            ip_trs = selector.css(<span class="string">'#ip_list tr'</span>)</span><br><span class="line">            ip_list = []</span><br><span class="line">            <span class="keyword">for</span> tr <span class="keyword">in</span> ip_trs[<span class="number">1</span>:]:</span><br><span class="line">                td_text = tr.css(<span class="string">'td::text'</span>).extract()</span><br><span class="line">                ip = td_text[<span class="number">0</span>]</span><br><span class="line">                port = int(td_text[<span class="number">1</span>])</span><br><span class="line">                http_type = td_text[<span class="number">5</span>]</span><br><span class="line">                speed_str = tr.css(<span class="string">".bar::attr(title)"</span>).extract()[<span class="number">0</span>]</span><br><span class="line">                <span class="keyword">if</span> speed_str:</span><br><span class="line">                    speed = float(speed_str.split(<span class="string">'秒'</span>)[<span class="number">0</span>])</span><br><span class="line">                ip_list.append((ip, port, http_type, speed))</span><br><span class="line"></span><br><span class="line">            <span class="keyword">for</span> ip_info <span class="keyword">in</span> ip_list:</span><br><span class="line">                <span class="comment">#<span class="doctag">todo:</span>插入http_type的值得为空处理~~</span></span><br><span class="line">                cursor.execute(<span class="string">"insert into proxy_ip(ip,port,http_type,speed) values('&#123;0&#125;',&#123;1&#125;,'&#123;2&#125;',&#123;3&#125;) ON DUPLICATE KEY UPDATE http_type='&#123;4&#125;',speed=&#123;5&#125;"</span>.format(ip_info[<span class="number">0</span>],ip_info[<span class="number">1</span>],ip_info[<span class="number">2</span>], ip_info[<span class="number">3</span>], ip_info[<span class="number">2</span>], ip_info[<span class="number">3</span>]))</span><br><span class="line">                conn.commit()</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GetIp</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="comment"># 判断ip是否有效</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">judge_ip</span><span class="params">(self, ip, port, http_type)</span>:</span></span><br><span class="line">        http_url = <span class="string">'http://www.baidu.com'</span></span><br><span class="line">        proxy_url = <span class="string">'http://&#123;0&#125;:&#123;1&#125;'</span>.format(ip, port)</span><br><span class="line">        proxies = &#123;http_type:proxy_url&#125;</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            response = requests.get(http_url, proxies=proxies)</span><br><span class="line">        <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">            self.delete_ip(ip, port)</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">False</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">if</span> response.status_code != <span class="number">200</span>:</span><br><span class="line">                self.delete_ip(ip, port)</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">False</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">True</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">delete_ip</span><span class="params">(self, ip, port)</span>:</span></span><br><span class="line">        sql = <span class="string">'''</span></span><br><span class="line"><span class="string">            delete from proxy_ip where ip='&#123;0&#125;' and port=&#123;1&#125;</span></span><br><span class="line"><span class="string">        '''</span>.format(ip, port)</span><br><span class="line">        cursor.execute(sql)</span><br><span class="line">        conn.commit()</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">True</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_random_ip</span><span class="params">(self)</span>:</span></span><br><span class="line">        sql = <span class="string">'''</span></span><br><span class="line"><span class="string">            select ip,port,http_type from proxy_ip where speed&lt;2 and (http_type='HTTP' or http_type='HTTPS') order by rand() limit 1</span></span><br><span class="line"><span class="string">        '''</span></span><br><span class="line">        cursor.execute(sql)</span><br><span class="line">        ip_info = cursor.fetchall()</span><br><span class="line">        <span class="keyword">if</span> len(ip_info) &lt;= <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">False</span></span><br><span class="line">        ip = ip_info[<span class="number">0</span>][<span class="number">0</span>]</span><br><span class="line">        port = ip_info[<span class="number">0</span>][<span class="number">1</span>]</span><br><span class="line">        http_type = ip_info[<span class="number">0</span>][<span class="number">2</span>]</span><br><span class="line">        result = self.judge_ip(ip, port, http_type)</span><br><span class="line">        <span class="keyword">if</span> result == <span class="keyword">True</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">'&#123;0&#125;://&#123;1&#125;:&#123;2&#125;'</span>.format(http_type, ip, port)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> self.get_random_ip()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">"__main__"</span>:</span><br><span class="line">    <span class="keyword">if</span> len(sys.argv) == <span class="number">2</span> <span class="keyword">and</span> sys.argv[<span class="number">1</span>] == <span class="string">'add_ip'</span>:</span><br><span class="line">        add_ip()</span><br><span class="line">        print(<span class="string">'success'</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        getip = GetIp()</span><br><span class="line">        random_ip = getip.get_random_ip()</span><br><span class="line">        print(random_ip)</span><br></pre></td></tr></table></figure>
<h4 id="Piplines"><a href="#Piplines" class="headerlink" title="Piplines"></a>Piplines</h4><h5 id="Piplines-配置"><a href="#Piplines-配置" class="headerlink" title="Piplines 配置"></a>Piplines 配置</h5><p>settings.py中的pipline 配置：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#值越小，优先级越高</span></span><br><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">    <span class="comment"># 自动下载图片</span></span><br><span class="line">   <span class="comment"># 'scrapyspiders.pipelines.ArticleImagePipeline':2,</span></span><br><span class="line">   <span class="string">'scrapyspiders.pipelines.MysqlTwistedPipeline'</span>:<span class="number">3</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h5 id="MysqlTwistedPipeline"><a href="#MysqlTwistedPipeline" class="headerlink" title="MysqlTwistedPipeline"></a>MysqlTwistedPipeline</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> MySQLdb</span><br><span class="line"><span class="keyword">import</span> MySQLdb.cursors</span><br><span class="line"><span class="keyword">from</span> twisted.enterprise <span class="keyword">import</span> adbapi</span><br><span class="line"></span><br><span class="line"><span class="comment"># 异步插入Mysql</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MysqlTwistedPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, dbpool)</span>:</span></span><br><span class="line">        self.dbpool = dbpool</span><br><span class="line"></span><br><span class="line"><span class="meta">    @classmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">from_settings</span><span class="params">(cls, settings)</span>:</span></span><br><span class="line">        dbparams = dict(</span><br><span class="line">            host = settings[<span class="string">'MYSQL_HOST'</span>],</span><br><span class="line">            db = settings[<span class="string">'MYSQL_DBNAME'</span>],</span><br><span class="line">            user = settings[<span class="string">'MYSQL_USER'</span>],</span><br><span class="line">            passwd = settings[<span class="string">'MYSQL_PASSWD'</span>],</span><br><span class="line">            charset=<span class="string">'utf8'</span>,</span><br><span class="line">            cursorclass=MySQLdb.cursors.DictCursor,</span><br><span class="line">            use_unicode=<span class="keyword">True</span></span><br><span class="line">        )</span><br><span class="line">        dbpool = adbapi.ConnectionPool(<span class="string">'MySQLdb'</span>, **dbparams)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> cls(dbpool)</span><br><span class="line"></span><br><span class="line">		<span class="comment"># 必须要实现的方法</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        query = self.dbpool.runInteraction(self.do_insert, item)</span><br><span class="line">        query.addErrback(self.handler_error,  item, spider)    <span class="comment">#插入异常</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">handler_error</span><span class="params">(self, failure, item, spider)</span>:</span></span><br><span class="line">        print(failure)</span><br><span class="line">        <span class="comment"># print(item)</span></span><br><span class="line">        <span class="comment"># print(spider)</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">do_insert</span><span class="params">(self, cursor, item)</span>:</span></span><br><span class="line">        insert_sql, params = item.get_insert_sql()</span><br><span class="line">        cursor.execute(insert_sql, params)</span><br></pre></td></tr></table></figure>
<h3 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h3><p>Scrapy框架的原理及简单使用： <a href="https://blog.csdn.net/Awangbsi/article/details/80749046" target="_blank" rel="noopener">https://blog.csdn.net/Awangbsi/article/details/80749046</a><br>《精通scrapy网络爬虫》<br>分布式爬虫搜索引擎：<br><a href="https://github.com/mtianyan/FunpySpiderSearchEngine" target="_blank" rel="noopener">https://github.com/mtianyan/FunpySpiderSearchEngine</a><br><a href="https://github.com/pujinxiao/project_pjx" target="_blank" rel="noopener">https://github.com/pujinxiao/project_pjx</a></p>

      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/d801fc43.html" title="Scrapy 框架的原理以及简单使用">http://blog.yunshu168.com/posts/d801fc43.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/爬虫/" rel="tag"># 爬虫</a>
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/7b68ab5b.html" rel="next" title="JSONP 跨域的原理">
                <i class="fa fa-chevron-left"></i> JSONP 跨域的原理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/9170d4fe.html" rel="prev" title="一些面试题">
                一些面试题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#介绍"><span class="nav-number">1.</span> <span class="nav-text">介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Scrapy-框架工作原理"><span class="nav-number">2.</span> <span class="nav-text">Scrapy 框架工作原理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#组件"><span class="nav-number">2.1.</span> <span class="nav-text">组件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Scrapy的执行流程"><span class="nav-number">2.2.</span> <span class="nav-text">Scrapy的执行流程</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Spider-实例"><span class="nav-number">3.</span> <span class="nav-text">Spider 实例</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#入口"><span class="nav-number">3.1.</span> <span class="nav-text">入口</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Spider"><span class="nav-number">3.2.</span> <span class="nav-text">Spider</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#Spider-Middleware"><span class="nav-number">3.2.1.</span> <span class="nav-text">Spider Middleware</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#获取代理ip"><span class="nav-number">3.2.2.</span> <span class="nav-text">获取代理ip</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Piplines"><span class="nav-number">3.3.</span> <span class="nav-text">Piplines</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#Piplines-配置"><span class="nav-number">3.3.1.</span> <span class="nav-text">Piplines 配置</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#MysqlTwistedPipeline"><span class="nav-number">3.3.2.</span> <span class="nav-text">MysqlTwistedPipeline</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考资料"><span class="nav-number">4.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
